package plugins

import (
	"consul_grpc/service"
	"time"

	"github.com/go-kit/kit/log"
)

//日志打印中间件
type loggingMiddleware struct {
	service.Service
	logger log.Logger
}

//在原有的服务基础上包装一层日志打印的逻辑仍返回同一服务实例
func LoggingMiddleware(logger log.Logger) service.ServiceMiddleware {
	return func(next service.Service) service.Service {
		return loggingMiddleware{next, logger}
	}
}

func (mw loggingMiddleware) HealthCheck() bool {
	result := true
	defer func(begin time.Time) {
		mw.logger.Log(
			"function", "HealthChcek",
			"result", result,
			"took", time.Since(begin),
		)
	}(time.Now())

	return result
}
func (mw loggingMiddleware) Greet(name string) string {
	result := mw.Service.Greet(name)
	defer func(begin time.Time) {
		mw.logger.Log(
			"function", "HealthChcek",
			"name", name,
			"result", result,
			"took", time.Since(begin),
		)
	}(time.Now())
	return result
}
func (mw loggingMiddleware) Discovery(serviceName string) (string, error) {
	result, err := mw.Service.Discovery(serviceName)
	defer func(begin time.Time) {
		mw.logger.Log(
			"function", "HealthChcek",
			"service_name", serviceName,
			"result", result,
			"took", time.Since(begin),
		)
	}(time.Now())
	return result, err
}
